package com.cloudxingkong.dianyinke.Student.Fragment;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Fragment.BaseFragment;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Adapter.DfkAdapter;
import com.cloudxingkong.dianyinke.Student.Ui.MyChange;
import com.cloudxingkong.dianyinke.Student.bean.QbfkEntity;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 待付款fragment
 */
public class DFK_Fragment extends BaseFragment implements DfkAdapter.onCallback {
    private List<QbfkEntity.ListBean> list;
    private ListView listView;
    private DfkAdapter adapter;
    private SharedPreferences sharedPreferences;
    private ProgressDialog progressDialog;
    private View view;
    private int orderId;
    private int orderId2;
    private getIsPayed isPayed;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_qbfk_, null);

        init();
        loadData();
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        isPayed= ((MyChange) activity);
    }

    private void loadData() {
        progressDialog.setMessage("正在加载...");
        progressDialog.show();
        String sessionid = CookieHelper.getSessionID(sharedPreferences);
        String upLoadUrl = ThisUri.SERVER_YUMING + StudentUri.DEMANDORDER;
        RequestParams params = new RequestParams(upLoadUrl);
        params.addHeader("cookie", sessionid);
        params.addBodyParameter("status", "1");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test", "待付款" + result);
                Message message = handler.obtainMessage();
                message.what = 1;
                message.obj = result;
                handler.sendMessage(message);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler handler = new Handler() {
        private boolean isSuccess;
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String state = (String) msg.obj;
                    if (state != null) {
                        Gson gson = new Gson();
                        QbfkEntity entity = gson.fromJson(state, QbfkEntity.class);
                        list.addAll(entity.getList());
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        progressDialog.dismiss();
                    } else {
                        Toast.makeText(getContext(), "您还没有兑换商品，赶快去兑换吧！！！", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    private void init() {
        listView = (ListView) view.findViewById(R.id.lv_qbfk);
        list = new ArrayList<>();
        adapter = new DfkAdapter(list, getActivity(), this);
        sharedPreferences = getActivity().getSharedPreferences("data_dyk", 0);
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.setTitle(null);
    }

    //取消订单的点击事件
    @Override
    public void onClick_quxiaodingdan(final TextView tv1, final int position) {
        orderId = list.get(position).getId();
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                new AlertDialog.Builder(getContext())
                        .setTitle("待付款")
                        .setMessage("亲:是否要取消订单...")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                LoadCancelOrder(tv1);
                            }
                        }).setNegativeButton("取消", null).create().show();
            }
        });
    }

    //取消订单
    private void LoadCancelOrder(final TextView v) {
        progressDialog.setMessage("正在取消...");
        progressDialog.show();
        String sessionid = CookieHelper.getSessionID(sharedPreferences);
        String upLoadUrl = ThisUri.SERVER_YUMING + StudentUri.CANCELORDER;
        RequestParams params = new RequestParams(upLoadUrl);
        params.addHeader("cookie", sessionid);
        params.addBodyParameter("id", orderId + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test", "删除订单" + result);
                HashMap<String, Object> jsonFromLogin2 = LoginJsonUtils.getJsonFromLogin(result);
                Object success2 = jsonFromLogin2.get("success");
                boolean isSuccess = (boolean) success2;
                if (isSuccess == true) {
                    Toast.makeText(getContext(), "取消成功", Toast.LENGTH_SHORT).show();
                    v.setText("已取消");
                    v.setClickable(false);
                    loadData();
                    progressDialog.dismiss();
                } else {
                    Toast.makeText(getContext(), "取消失败", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
                progressDialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {

            }
        });
    }

    //支付的点击事件
    @Override
    public void onClick_zhifu(final TextView tv2, int position) {
        orderId2 = list.get(position).getId();
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                new AlertDialog.Builder(getContext())
                        .setTitle("待付款")
                        .setMessage("亲:商品已下单，点击确认后,电音课马上为您发货！！！")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                LoadPay(tv2);
                            }
                        }).setNegativeButton("取消", null).create().show();
            }
        });
    }

    private void LoadPay(final TextView v) {
        progressDialog = ProgressDialog.show(getActivity(), null, "正在为您提交信息...", true, false);
        String sessionid = CookieHelper.getSessionID(sharedPreferences);
        String upLoadUrl = ThisUri.SERVER_YUMING + StudentUri.ORDERPAY;
        RequestParams params = new RequestParams(upLoadUrl);
        params.addHeader("cookie", sessionid);
        params.addBodyParameter("id", orderId2 + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test", "积分支付" + result);
                HashMap<String, Object> jsonFromLogin2 = LoginJsonUtils.getJsonFromLogin(result);
                Object success2 = jsonFromLogin2.get("success");
                boolean isSuccess = (boolean) success2;
                if (isSuccess == true) {
                    Toast.makeText(getContext(), "支付成功", Toast.LENGTH_SHORT).show();
                    v.setText("已支付");
                    v.setClickable(false);
                    loadData();
                    Constans.REFRESH_INDEX = 10087;
                    isPayed.getPayed(Constans.REFRESH_INDEX);
                    progressDialog.dismiss();
                    //loadData();
                } else {
                    Toast.makeText(getContext(), "支付失败", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
                progressDialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public interface getIsPayed{
        void getPayed(int index);
    }

}
